package com.cyurs.netty.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author: Cyrus
 * @CreateDate: 2020/11/17
 */
public class NIOServer {
    public static void main(String[] args) throws Exception{
        //开启ServerSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //绑定端口号
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        //设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        //开启Selector  ->底层WindowsSelectorImpl实现
        Selector selector = Selector.open();
        //将serverSocketChannel注册到selector上，事件为OP_ACCEPT
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true) {
            if (selector.select(1000)==0) {//若没有发生时间
                System.out.println("服务器等待1s没有客户端链接！");
                continue;
            }
            //selector监听客户端行为
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            //通过迭代器遍历selectionKeys获取selectionKey对应的事件
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();
                if (key.isAcceptable()) {//如果是OP_ACCEPT事件
                    //给该户科短生成一个socketChannel
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端连接成功，生成一个socketChannel"+socketChannel.hashCode());
                    //设置为非阻塞
                    socketChannel.configureBlocking(false);
                    //将socketChannel注册到selector，并关联一个Buffer
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if (key.isReadable()) { //如果是OP_READ事件
                    //通过key反向获取通道
                    SocketChannel channel = (SocketChannel) key.channel();
                    //通道与buffer进行关联，将通道数据读到buffer
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    channel.read(buffer);
                    System.out.println("from 客户端"+new String(buffer.array()));
                }
                //手动移出selectionKey避免重复操作
                keyIterator.remove();
            }
        }
    }
}
